//
//  TimerBlock.m
//  etionMisc
//
//  Created by wu jingxing on 12-8-9.
//  Copyright (c) 2012年 GuangZhouXuanWu. All rights reserved.
//

#import "XMSTimerBlock.h"

@interface XMSTimerBlock ()
{
    BOOL _bRepeat;
    NSTimer* _timer;
    timerblock _timeblock;
}

@property(nonatomic,retain) NSTimer* timer;

@end

@implementation XMSTimerBlock

@synthesize timer = _timer;

-(void)setBlock:(timerblock)block
{
    if(block!=NULL)
        _timeblock=(__bridge_mm timerblock)Block_copy((__bridge_mm void*)block);
}

-(void)setRepeat:(BOOL)bRepeat
{
    _bRepeat=bRepeat;
}

-(id)initScheduledTimerWithTimeInterval:(NSTimeInterval)interval repeats:(BOOL)bRepeat block:(timerblock)block
{
    self=[super init];
    
    [self setBlock:block];
    [self setRepeat:bRepeat];
    
    self.timer=[NSTimer scheduledTimerWithTimeInterval:interval target:self selector:@selector(blockAction:) userInfo:nil repeats:bRepeat];
    
    return self;
}

-(id)initTimerWithTimeInterval:(NSTimeInterval)interval repeats:(BOOL)bRepeat block:(timerblock)block
{
    self=[super init];
    
    [self setBlock:block];
    [self setRepeat:bRepeat];
    
    self.timer=[NSTimer timerWithTimeInterval:interval target:self selector:@selector(blockAction:) userInfo:nil repeats:bRepeat];
    
    return self;
}

-(void)setFireDateFromNowToTimeInterval:(NSTimeInterval)nSecond runLoop:(NSRunLoop*)runLoop
{
    [_timer setFireDate:[NSDate dateWithTimeIntervalSince1970:[[NSDate date] timeIntervalSince1970]+nSecond]];
    [runLoop addTimer:_timer forMode:NSDefaultRunLoopMode];
}

-(void)setFireDateFromNowToTimeInterval:(NSTimeInterval)nSecond
{
    [self setFireDateFromNowToTimeInterval:nSecond runLoop:[NSRunLoop mainRunLoop]];
}

-(void)setFireDate:(NSDate*)date
{
    [_timer setFireDate:date];
}

-(void)blockAction:(id)sender
{
    timerblock t = [[_timeblock retain_mm] autorelease_mm];
    (void)t;
    _timeblock(self);
}

-(void)invalidate
{
    [_timer invalidate];
    if(_timeblock!=NULL)
    {
        Block_release((__bridge_mm void*)_timeblock);
    }
    _timeblock=NULL;
    [_timer release_mm];
    _timer=nil;
}

-(void)fireTimeOnRunLoop:(NSRunLoop*)runLoop forMode:(NSString*)mode
{
    [runLoop addTimer:_timer forMode:mode];
}

+(uint64_t)functionProcess:(void(^)())block
{
    mach_timebase_info_data_t info;
    if(mach_timebase_info(&info)!=KERN_SUCCESS)
        return -1;
    uint64_t start=mach_absolute_time();
    block();
    uint64_t end=mach_absolute_time();
    return end-start;
}

-(void)dealloc
{
    [self invalidate];
    superdealloc_mm;
}

@end
